//
//  WBPictureSelectorController.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/22.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit

let coloumCount: CGFloat = 3
let selectorMargin : CGFloat = 4
let selectorItemWidth : CGFloat = (kScreenW - 4*selectorMargin)/3

private let itemCount = 9

private let itemID = "Cell"

class WBPictureSelectorController: UICollectionViewController {

    //定义一个数组来保存用户在相册中选择的图片
    var selectorImages : [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.register(WBPictureSelectorCell.self, forCellWithReuseIdentifier: itemID)
    }
    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectorImages.count + 1
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:itemID , for: indexPath) as! WBPictureSelectorCell
//        cell.backgroundColor = #colorLiteral(red: 1, green: 0.1892277598, blue: 0.5876249075, alpha: 1)
        cell.delegate = self
        if indexPath.item == self.selectorImages.count{
            cell.btnImage = nil
        }else{
        cell.btnImage = self.selectorImages[indexPath.item]
        }
        return cell
    }
    
    
}

//MARK - 分类遵守自定义协议 实现协议方法
extension WBPictureSelectorController : WBPictureSelectorCellDelegate,UINavigationControllerDelegate {
    //实现代理方法
    func willAddPicture(cell: WBPictureSelectorCell?) {
//        print("点击了添加图片")
        let picker = UIImagePickerController()
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
    }
    
    func willRemovePicture(cell: WBPictureSelectorCell) {
//        print("点击了移除图片")
        //根据cell拿到下标,然后删除对应数组的图片
        guard let index = collectionView?.indexPath(for: cell) else {
            return
        }
        
        self.selectorImages.remove(at: index.item)
        
        self.collectionView?.reloadData()
        //没了就隐藏
        self.view.isHidden = selectorImages.count == 0
    }
}

//MARK - 分类遵守图片选择控制器的协议
extension WBPictureSelectorController : UIImagePickerControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //选择图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage

        //添加到数组中
        self.selectorImages.append(image.scaleImage(width: kScreenW))
        //需要自己手动dismiss控制器
        dismiss(animated: true, completion: {
            //刷新collectionview
            self.collectionView?.reloadData()
        })
        
    }
    
}





//MARK - 自定义collectionviewcell
//协议
@objc protocol WBPictureSelectorCellDelegate:NSObjectProtocol {
    
    @objc optional func willAddPicture(cell : WBPictureSelectorCell?)
    
    @objc optional func willRemovePicture(cell: WBPictureSelectorCell)
}

class WBPictureSelectorCell: UICollectionViewCell {
    
    //设置代理 协议方法可选  代理也要加问好可选类型
    weak var delegate : WBPictureSelectorCellDelegate?
    
    var btnImage : UIImage?{
        didSet {
            addButton.setImage(btnImage, for: .normal)
            //移除按钮的隐藏
            removeButton.isHidden = btnImage == nil
            
            //有图的时候隐藏后面的
            let backImage: UIImage? = (btnImage == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            addButton.setBackgroundImage(backImage, for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加照片的button的点击事件
    @objc private func addBtnDidClick(){
        //利用代理将消息传入控制器,控制器进行跳转到图片选择控制器
        delegate?.willAddPicture!(cell: self)
    }
    @objc private func removeBtnDidClick(){
        
        delegate?.willRemovePicture!(cell: self)
    }
    
    private func setupUI(){
        self.contentView.addSubview(addButton)
        self.contentView.addSubview(removeButton)
        
        
        addButton.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView)
        }
        removeButton.snp.makeConstraints { (make) in
            make.top.right.equalTo(self.contentView)
        }
        
        addButton.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        
        removeButton.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
    }

    //懒加载控件
    lazy var addButton : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .highlighted)
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    lazy var removeButton : UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
}
